package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;

  @Autowired
  private UserAccountDetailMapper userAccountDetailMapper;

  @Resource
  private OrderInfoFeignClient orderInfoFeignClient;
  /**
   * 初始化账户
   * @param userId
   */
  @Override
  public void initUserAccount(Long userId) {
    //查询这个用户是否初始化过账户: 防止消息重复消费
    long row = count(new LambdaQueryWrapper<UserAccount>()
                               .eq(UserAccount::getUserId, userId));
    if(row > 0){
      return;
    }
    //初始化
    UserAccount userAccount = new UserAccount();
    userAccount.setUserId(userId);
    if(!save(userAccount)){
      throw new GuiguException(201, "初始化失败!!!");
    }
  }

  /**
   * 记录消费
   * @param orderNo
   */
  @Override
  public void insertUserAccountDetail(String orderNo) {
    //查询订单的详细信息
    OrderInfo orderInfo = orderInfoFeignClient.getOrderInfo(orderNo);
    if(orderInfo == null){
      return;
    }
    //声明DO
    UserAccountDetail userAccountDetail = new UserAccountDetail();
    userAccountDetail.setUserId(orderInfo.getUserId());
    userAccountDetail.setTitle(orderInfo.getOrderTitle());
    userAccountDetail.setTradeType("1204"); // 消费
    userAccountDetail.setAmount(orderInfo.getOrderAmount());
    userAccountDetail.setOrderNo(orderNo);
    if(userAccountDetailMapper.insert(userAccountDetail) <= 0){
      throw new GuiguException(201, "保存消费记录失败");
    }
  }
}
